package com.chinda.common.service;

import com.chinda.common.exception.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 共通Service
 *
 * @author Wang Chinda
 * @date 2020/8/8
 * @see
 * @since 1.0
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class ServiceImpl<D extends JpaRepository<T, Long>, T> {

    @Autowired
    private D baseDao;

    /**
     * 获取全部数据
     *
     * @return
     */
    public List<T> queryAll() {
        return baseDao.findAll();
    }

    /**
     * 获取数据详情
     *
     * @param id
     * @return
     */
    public T getOne(Long id) {
        return baseDao.findById(id).orElseThrow(() -> new RRException("该数据不存在"));
    }

    /**
     * 保存数据
     *
     * @param t
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public T save(T t) {
        return baseDao.save(t);
    }

    /**
     * 删除数据
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void remove(Long id) {
        baseDao.deleteById(id);
    }
}
